from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from rest_framework.generics import GenericAPIView

from datetime import date

from apps.users.models import User
from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.home import CategoryCountSerializer

class UserTotalCountView(APIView):
    #用户总量
    permission_classes = [IsAdminUser]

    def get(self,request):
        count = User.objects.all().count()
        return Response({"count": count})


class DailyUserAddCountAPIVIew(GenericAPIView):
    #日增用户
    permission_classes = [IsAdminUser]

    def get(self,request):
        today = date.today()
        count = User.objects.filter(date_joined__gte = today).count()
        return Response({"count": count})


class DailyUserActiveCountAPIVIew(GenericAPIView):
    #日活用户
    permission_classes = [IsAdminUser]

    def get(self,request):
        today = date.today()
        count = User.objects.filter(last_login__gte=today).count()
        return Response({"count": count,"date":today})


class UserDailyOrderCountAPIView(APIView):
    #日下单用户量

    def get(self,request):
        today = date.today()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        return Response({"count":count})


from datetime import timedelta
class UserMonthCountAPIView(APIView):
    #月增用户
    permission_classes = [IsAdminUser]

    def get(self,request):
        today = date.today()
        start_date = today-timedelta(days=30)
        date_list = []

        for i in range(30):
            start_time = start_date+timedelta(days=i)
            end_time = start_date+timedelta(days=(i+1))

            count = User.objects.filter(date_joined__gte=start_time,
                                        date_joined__lt=end_time).count()
            date_list.append({
                "count":count,
                "date":start_time
            })
        return Response(date_list)


class CategoryCountAPIView(APIView):
    #日分类商品访问量
    permission_classes = [IsAdminUser]

    def get(self,request):
        today = date.today()
        gvc = GoodsVisitCount.objects.filter(date__gte=today)
        s = CategoryCountSerializer(instance=gvc,many=True)
        return Response(s.data)




